<template>
  <l-layout class="l-tab-page" v-show="!lr_loadPage" :left="240">
    <template #left>
      <l-panel :title="$t('接口分类')" style="padding-right: 0">
        <el-tree
          ref="mytree"
          v-loading="treeLoading"
          node-key="value"
          default-expand-all
          :expand-on-click-node="false"
          :data="apiArr"
          :props="defaultProps"
          @node-click="handleNodeClick"
        >
          <span class="lr-tree-node" slot-scope="{ node }">
            <i class="fa fa-sitemap"></i>
            {{ $t(node.label) }}
          </span>
        </el-tree>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('请输入关键字查询')"
            v-model="searchWord"
            @keyup.enter.native="hanleSearch"
            size="mini"
          >
            <el-button slot="append" icon="el-icon-search" @click="hanleSearch"></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns @click="handleAdd()">
          <l-excel-btns></l-excel-btns>
        </l-tool-btns>
      </template>
      <l-table
        :loading="tableLoading"
        :columns="lr_getPageColumns(columns)"
        :dataSource="tableShowData"
        row-key="f_Id"
        :isPage="true"
        :pageTotal="tableTotal"
        :tablePage.sync="tableCurrentPage"
        @loadPageData="turnTablePage"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        default-expand-all
      >
        <template v-slot:isArray="scope">
          {{ getIsArray(scope.row) }}
        </template>
        <!--
                <template v-slot:f_TenantType="scope" >
                    {{scope.row.f_TenantType==0 ?"普通租户":"系统平台租户"}}
                </template>
            	-->
        <l-table-btns :btns="tableBtns" @click="lr_handleTableBtnClick"></l-table-btns>
      </l-table>
    </l-panel>

    <l-dialog
      :title="formTitle"
      :visible.sync="formVisible"
      @ok="handleSave"
      @close="handleCloseForm"
      @opened="handleOpenedForm"
      :width="600"
    >
      <my-form ref="form" @showCityName="showForm2"></my-form>
    </l-dialog>

    <l-dialog title="数据结构" :visible.sync="formVisible2" :width="800" @ok="hideForm2" @close="hideForm2">
      <my-entity ref="entity" @childEntityForm="entityFormChange"></my-entity>
    </l-dialog>
  </l-layout>
</template>

<script>
const api = window.$api.data.dataInterface;
const api2 = window.$api.data.datainterfacecategory;
import MyForm from "./form";
import MyEntity from "./entity";
export default {
  components: {
    MyForm,
    MyEntity,
  },
  data() {
    return {
      lr_isPage: true,
      // 表格
      columns: [
        { label: "接口名称", prop: "f_Name", minWidth: "120" },
        { label: "接口连接", prop: "f_Url", minWidth: "240" },
        { label: "数据结构", prop: "Type", minWidth: "120" },
        { label: "是否集合", prop: "isArray", minWidth: "120" },
        { label: "备注", prop: "f_Description", minWidth: "120" },
      ],
      tableBtns: [
        { prop: "Edit", label: "编辑" },
        { prop: "Delete", label: "删除" },
      ],
      tableLoading: false,
      searchWord: "",
      tableShowData: [],
      tableData: [],

      formVisible: false,
      formVisible2: false,
      formTitle: "",
      formEditRow: null,
      formEdit: false,

      //分页
      tableTotal: 0,
      tablePageSize: 50,
      tableCurrentPage: 1,
      keyWord: "",

      apiArr: [],
      defaultProps: {
        children: "children",
        label: "label",
      },
      treeLoading: false,
      f_CategoryId: "",
    };
  },
  mounted() {
    //var data = await this.$awaitWraper(api2.getTenantList());
    this.$nextTick(() => {
      //this.loadTable();
      var _this = this;
      api2
        .getList()
        .then((res) => {
          res.data.data.forEach(function (v) {
            v.label = v.f_Name;
            v.value = v.f_Id;
          });
          var list = _this.$deepClone(res.data.data);
          //console.log(res.data.data);
          _this.apiArr = this.lr_apiTree(list);
          _this.loadTablePageData();
        })
        .catch(() => {});
    });
  },
  computed: {},
  methods: {
    getIsArray(row) {
      let responseType = JSON.parse(row.f_ResponseType);
      if (responseType) {
        return responseType.isArray ? "是" : "否";
      } else {
        return "否";
      }
    },
    lr_apiTree(data) {
      data = data || [];
      return this.$toTree(data, "f_Id", "f_ParentId", "f_Id", "f_Name");
    },

    handleNodeClick(node) {
      this.loading = true;
      this.f_CategoryId = node.f_Id;
      this.loadTablePageData();
    },

    loadTablePageData(isNotFirst) {
      if (isNotFirst) {
        this.tableCurrentPage = 1;
        this.searchWord = "";
        this.tableData = [];
      }
      this.tableLoading = true;
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        keyword: this.searchWord,
        f_CategoryId: this.f_CategoryId,
        f_EnabledMark: 1,
      };
      this.tableData = [];
      api
        .getPage(queryData)
        .then((res) => {
          const data = this.$deepClone(res.data.data);
          data.rows.forEach(function (v) {
            var type = JSON.parse(v.f_ResponseType);
            v.Type = type.dataTypeFullName;
          });
          this.tableData = this.lr_apiTree(data.rows);
          //console.log(this.tableData);
          this.tableTotal = data.records;
          this.tableShowData = this.tableData;
          this.tableLoading = false;
        })
        .catch(() => {
          this.tableData = [];
          this.tableLoading = false;
        });
    },
    turnTablePage({ rows }) {
      this.tablePageSize = rows;
      this.loadTablePageData(true);
    },
    hanleSearch() {
      this.loadTablePageData();
    },

    // 表单部分
    handleAdd() {
      this.formEdit = false;
      this.showForm("新增接口");
    },
    handleEdit($index, row) {
      this.formEdit = true;
      this.formEditRow = row;
      this.showForm("编辑接口信息");
    },
    handleDelete($index, row) {
      this.$confirm("此操作将永久删除该数据, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          api.remove(row.f_Id).then(() => {
            this.tableShowData.splice($index, 1);
            this.$message({
              type: "success",
              message: "删除成功!",
            });
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    async handleSave(showLoading, hideLoading) {
      showLoading();
      if (!(await this.$refs.form.validateForm())) {
        hideLoading();
        return;
      }
      const formData = this.$refs.form.getForm();
      if (!formData) {
        this.$message({
          type: "error",
          message: "json字符串校验错误!",
        });
        return;
      }
      if (this.formEdit) {
        // 修改数据

        api
          .update(formData.f_Id, formData)
          .then(() => {
            hideLoading();
            this.formVisible = false;
            this.$message({
              type: "success",
              message: "更新成功!",
            });
            this.loadTablePageData(true);
          })
          .catch(() => {
            hideLoading();
          });
      } else {
        // 新增数据

        api
          .add(formData)
          .then(() => {
            hideLoading();
            this.formVisible = false;
            this.$message({
              type: "success",
              message: "添加成功!",
            });
            this.loadTablePageData(true);
          })
          .catch(() => {
            hideLoading();
          });
      }
    },
    handleOpenedForm() {
      if (this.formEdit) {
        //console.log("this.formEditRow", this.formEditRow);
        this.$refs.form.setForm(this.formEditRow);
      }
    },
    handleCloseForm() {
      this.$refs.form.resetForm();
    },
    showForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },

    showForm2() {
      this.formVisible2 = true;
      //console.log(110);
    },

    hideForm2() {
      this.formVisible2 = false;
    },

    entityFormChange(e) {
      //console.log(e);
      this.formVisible2 = false;
      this.$refs.form.entityFormChange(e);
    },
  },
};
</script>
